package gemini.castor.ui.client.page.widget.distributorid;

import gemini.castor.ui.client.page.widget.NumberFieldStandard;
import gemini.castor.ui.client.page.widget.TextFieldTextNumber;
import gemini.castor.ui.client.utils.UiConstants;

import java.util.Iterator;
import java.util.Set;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.validation.client.InvalidConstraint;
import com.google.gwt.validation.client.interfaces.IValidator;

public class DistributorIdWidget extends Composite {

	@UiTemplate("DistributorIdWidget.ui.xml")
	interface MyUiBinder extends UiBinder<Panel, DistributorIdWidget> {
	}

	private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

	private IValidator<DistributorIdObject> validator;
	private DistributorIdObject object;

	public void setDistributorIdObject(DistributorIdObject object) {
		this.object = object;
	}

	public DistributorIdWidget() {
		initWidget(binder.createAndBindUi(this));
		validator = GWT.create(DistributorIdObject.class);
		tbxId.setMaxLength(UiConstants.MAX_LEN_DIS_ID);
	}

	@UiField
	TextBox tbxFullName;

	@UiField
	TextFieldTextNumber  tbxId;

	@UiField
	NumberFieldStandard  tbxPhone;

	public boolean isValidate() {
		resetStyle();
		bind();
		boolean result = true;
		Set<InvalidConstraint<DistributorIdObject>> invalidConstraints = validator
				.validate(object);
		Iterator<InvalidConstraint<DistributorIdObject>> it = invalidConstraints
				.iterator();

		while (it.hasNext()) {
			if (result) {
				result = false;
			}
			InvalidConstraint<DistributorIdObject> ic = it.next();
			showError(ic.getItemName(), ic.getMessage());
		}

		return result;
	}

	private void resetStyle() {
		tbxFullName.removeStyleDependentName("error");
		tbxId.removeStyleDependentName("error");
	}

	private void showError(String widgetName, String errorString) {
		if (widgetName.equals("fullname")) {
			tbxFullName.addStyleDependentName("error");
			
			
		} else if (widgetName.equals("distributorId")) {
			tbxId.addStyleDependentName("error");
		}
	}

	public void bind() {
		object.setFullname(tbxFullName.getValue());
		object.setDistributorId(tbxId.getValue());
		object.setCellPhone(tbxPhone.getValue());
	}

	public void reset() {
		resetStyle();
		resetValue();
	}
	
	public void resetValue() {
		tbxFullName.setValue("", true);
		tbxId.setValue("", true);
	}
}
